import httpx
from typing import Dict, List, Any
from datetime import datetime
import logging
import json

class LangflowService:
    def __init__(self, langflow_url: str):
        """Initialize LangflowService with Langflow API endpoint"""
        self.langflow_url = langflow_url
        self.logger = logging.getLogger(__name__)
        
    async def generate_kpi_params(
        self,
        user_question: str,
        current_time: datetime,
        metrics_data: Dict[str, Any],
        dimension_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        Call Langflow to generate KPI query parameters based on user input
        """
        try:
            # Prepare payload for Langflow
            payload = {
                "question": user_question,
                "current_time": current_time.isoformat(),
                "metrics": metrics_data,
                "dimensions": dimension_data
            }
            
            # Call Langflow API
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.langflow_url}/api/v1/generate-kpi-params",
                    json=payload
                )
                response.raise_for_status()
                
            return response.json()
            
        except Exception as e:
            self.logger.error(f"Error generating KPI params: {str(e)}")
            raise
            
    async def generate_plot_code(
        self,
        user_question: str,
        kpi_params: Dict[str, Any],
        dataframe_metadata: Dict[str, Any]
    ) -> str:
        """
        Call Langflow to generate Plotly visualization code
        """
        try:
            # Prepare payload for Langflow
            payload = {
                "question": user_question,
                "kpi_params": kpi_params,
                "df_metadata": dataframe_metadata
            }
            
            # Call Langflow API
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.langflow_url}/api/v1/generate-plot-code",
                    json=payload
                )
                response.raise_for_status()
                
            return response.json()["plot_code"]
            
        except Exception as e:
            self.logger.error(f"Error generating plot code: {str(e)}")
            raise